<?php

declare(strict_types=1);

namespace App\Job;
use App\Model\Device;
use App\Model\Normal;
use App\Services\Bolai\BlService;
use Hyperf\AsyncQueue\Job;
use Hyperf\Di\Annotation\Inject;
use Hyperf\Utils\ApplicationContext;
use Swoole\Server;

class IotEvent extends Job
{
    public $messageResult;

    public $fd;

    public $type;

    /**
     * 任务执行失败后的重试次数，即最大执行次数为 $maxAttempts+1 次
     */
    protected int $maxAttempts = 1;
    #[inject]
    protected BlService $blService;

    public function __construct($fd, $type,$messageResult = null)
    {
        $this->fd = $fd;
        $this->type = $type;
        $this->messageResult = $messageResult;
    }

    public function handle()
    {

        try{
            switch($this->type){
                case 'recv':
                    $server = ApplicationContext::getContainer()->get(Server::class);
                    // 检查连接是否存在
                    if ($server->exists($this->fd)) {
                        $this->blService->parse($this->messageResult)->handle($this->fd);
                    } else {
                        Normal::logger('fd---not found in queue', 'notify-event');
                    }
                    break;
                case 'open':
                    break;
                case 'close':
                    $this->blService->setOff($this->fd);
                    Normal::logger('fd--'.$this->fd.'----close', 'notify-event');
                    break;
                default:
                    //do something
                    break;

            }
        }catch (\Exception $e){
            Normal::logger($e->getMessage() . $e->getTraceAsString(),'notify-event');
        }
    }
}
